<template>
  <div class="boardBox1">
    <div class="flex-1 flex box-row-column ggpadzy20">
      <div class="flex box-align-center">
        <div class="flex-1 font17">上传文件</div>
        <div class="down_zi downpng" @click="downmb">下载模板</div>
      </div>
      <div class="flex box-align-center justify-content-center uploadk mt20">
        <el-upload
          class="avatar-uploader"
          ref="uploadRef"
          name="file"
          :limit="1"
          drag
          :auto-upload="false"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          action
          :multiple="false"
          :on-exceed="handleExceed"

          :file-list="filelist"
          :on-change="handleChansge"
        >

                  <!-- :before-upload="beforeUpload" -->
          <div class="flex box-row-column box-align-center">
            <el-icon size="30"><UploadFilled /></el-icon>
            <div class="el-upload_tip mt10">点击或者拖拽需要上传的文件</div>
            <div class="el-upload_tip mt10">只支持xIs、xIsx格式文件</div>
          </div>
        </el-upload>
      </div>

      <div class="mt20 impzi1">请确认以下字段系统识别无误：</div>
      <div class="impzi2">注意：系统默认读取表格第一行进行字段匹配</div>
      <el-table
        :data="list"
        border
        class="mt20"
        v-loading="loading"
        element-loading-background="rgba(0, 0, 0, 0.5)"
        element-loading-text="加载中..."
        header-row-class-name="table-header"
        style="overflow-y: auto; height: 200px"
      >
        <el-table-column label="您导入的表格" align="center" key="excel_header" prop="excel_header" />
        <el-table-column label="系统字段" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.db_field" placeholder="请选择"  clearable   @change="change(scope.row.db_field)">
              <el-option v-for="item in selectlist" :key="item.field" :label="item.comment" :value="item.field" :disabled="item.disabled"/>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer mt20" style="text-align: right">
        <el-button  @click="submitForm(2)" >仅导入新员工</el-button>

        <el-button type="primary" color="#01509f" @click="submitForm(1)" >确认导入</el-button>

      </span>
    </div>

    <div class="flex-1 flex box-row-column impborderleft ggpadzy20">
      <div class="font16">自定义导入步骤</div>

      <div class="importcontent mt20">
        自定义导入： 1.您可使用系统提供的模板或自定义表格导入员工信息
        <br />

        2.导入后请手动确认系统自动识别的字段匹配是否准确，若个别字段匹配错误您可手动调整
        <br />

        2.1以下字段为固定选项或有特殊识别要求，请注意匹配，否则可能导入失败
        <br />

        （1）户籍类型：本地城镇、外地城镇、本地农村、外地农村
        <br />

        （2）用工模式：全职、兼职、外包、零工、实习、劳务派遣、顾问、退休返聘、其他
        <br />

        （3）部门：若存在多级部门，则可在部门后增加若干列，如2级部门、3级部门
        <br />

        （4）试用期：无试用期、1个月、2个月、3个月、4个月、5个月、6个月
        <br />

        （5）劳动合同期：无固定期限、6个月、12个月、24个月、36个月或以上
        <br />

        （6）员工状态：正式、试用期
        <br />

        3.点击确认导入，即可完成员工信息导入
        <br />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, watch ,nextTick } from "@/TUIKit/adapter-vue";
  import { zidingyiupload, zidingyidaoru, template } from "@/api/cf";
  import { ElMessage, ElMessageBox } from "element-plus";
  import axios from "axios";
  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
  });
  const deptoptions = ref([]);
  const baseURL = "https://demo-api.niuyuwang.com/";
  const filelist = ref([]);
  const selectlist = ref([]);
  // const youruploadurl = ref("https://demo-api.niuyuwang.com/admin/Ajax/upload");
  const job_modeoptions = ref([]);
  const list = ref([]);
  const queryParams = ref({ name: "", dept_id: "", position: "", hired_time: "", job_status: "", mobile: "" });
  const emit = defineEmits<{ (event: "update:visible", value: boolean): void; (event: "chananniu", value: ""): void ;(event: "success", value: ""): void }>();
  const uploadRef = ref(null); // 引用 el-upload 组件

  // 获取表单引用
  const queryForm = ref(null);
  // 监听 localValue 的变化，通知父组件更新值
  watch(
    () => props.visible,
    newValue => {
      if (newValue) {
        getDepartmentlist().then(res => {
          deptoptions.value = res.data;
        });
      }
    }
  );

  const addvisible = ref(false);

  const selectedArrRef = ref(null);
  function handleChange(value) {
    selectedArrRef.value.togglePopperVisible();
  }
  function cancel() {
    emit("update:visible", false);

    emit("chananniu", "");
  }



  function change(e) {
        var idx = -1;
       selectlist.value.forEach((item, index)  => {
         list.value.forEach(element => {
            if (item.field == element.db_field) {
             item.disabled = true;
              idx = index
            }
          })
          if (idx != index) {
           item.disabled = false;
          } 
        });
    }

  function downmb() {
    template().then(res => {
      window.open(res.data.$zdyurl);
      ///  window.open(res.data);
    });
  }

  function submitForm(a) {
  //console.log(typeof list.value, "sgsgsg");

    if (list.value.length===0) {
      ElMessage({
        message: "请导入文件",
        grouping: true,
        type: "error",
      });
      return false
    }


    let arr = [...list.value];
    let token = localStorage.getItem("token");
    axios
      .post(
        baseURL + "hr/Userinfo/daoru",
        { array: arr,is_new: a},
        {
          headers: { token: token },
        }
      )
      .then(response => {
        // console.log(response.data);

        if (response.data.code == 1) {
          ElMessage({
            message: "导入成功",
            grouping: true,
            type: "success",
          });
          emit("update:visible", false);
          emit("success", "");
        } else {
          ElMessage({
            message: response.data.msg,
            grouping: true,
            type: "error",
          });
        }
      })
      .catch(error => {

            ElMessage({
            message: error,
            grouping: true,
            type: "error",
          });
      });

    // zidingyidaoru(arr).then(res => {
    //     ElMessage({
    //       message: res.msg,
    //       grouping: true,
    //       type: "success",
    //     });
    //     emit("update:visible", false);
    //     emit("success", "");
    //   });
  }

  function handleExceed(files, fileList) {
     uploadRef.value.clearFiles()

    nextTick(() => {
       uploadRef.value.handleStart(files[0])
    })
      // ElMessage({
      //   title: "错误",
      //   message: `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`,
      //   grouping: true,
      //   type: "error",
      // });
      //     filelist.value = fileList;
  }
  // beforeUpload(file) {
  //   // 如果fileList中已经存在文件，则先移除该文件
  //   if (this.fileList.length > 0) {
  //     this.fileList = []; // 清空已上传的文件列表
  //   }
  //   // 将新文件添加到fileList中
  //   this.fileList.push(file);
  //   // 返回false以阻止自动上传，因为我们将在handleRemove中手动处理上传
  //   return false;
  // }


  function handleChansge(file, fileList) {

    let name = file.name;

    if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
      ElMessage({
        title: "错误",
        message: "上传文件只能为excel文件，且为xlsx,xls格式",
        grouping: true,
        type: "error",
      });
      return false;
    }

    let token = localStorage.getItem("token");
    filelist.value = fileList;
    let formData = new FormData();
    formData.append("excel", file.raw);

    axios
      .post(baseURL + "hr/Userinfo/upload", formData, {
        headers: { "Content-Type": "multipart/form-data", token: token },
      })
      .then(response => {
        if (response.data.code == 1) {
          // console.log(response.data.data.fieldComments, "sgsgsg");


        const arry=  response.data.data.fieldComments.map(item => {
               const obj={
                ...item,
                 disabled:true,
               }
              return obj;
           });
    
            console.log(arry, "sgsgsgsg");
       selectlist.value = arry;
          list.value = response.data.data.array;
        } else {
          ElMessage({
            message: response.data.msg,
            grouping: true,
            type: "error",
          });
        }
      })
      .catch(error => {
        console.error(error);
      });
    // this.$axios1.post(url, formData, config); //也可以这种 我这里是封装的
    // zidingyiupload(formData)
    //   .then(res=> {
    //     console.log(res,"sgsgsgsgsg");

    //     ElMessage({
    //       message: "上传成功",
    //       grouping: true,
    //       type: "success",
    //     });
    //   })
    //   .catch(err => {
    //     ElMessage({
    //       message: err,
    //       grouping: true,
    //       type: "error",
    //     });
    //   });
  }

  const childMethod = () => {
    filelist.value = [];
    selectlist.value = [];
    list.value = [];
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
  };

  defineExpose({
    childMethod,
  });
</script>

<style lang="scss" scoped>
.boardBox1 {
  display: flex;

  flex-wrap: wrap;
  justify-content: space-around;
  overflow-y: scroll;
  max-height: calc(100vh - 210px);
  color: #333;

  &::-webkit-scrollbar {
    display: none;
  }

  -ms-overflow-style: none;
  scrollbar-width: none;

  .tishi {
    font-size: 16px;
    color: #999;
    background-color: #f3f8fb;
    padding: 5px 10px;
    border-radius: 6px;
  }

  .font16 {
    font-size: 16px;
  }

  .el-upload_tip {
    font-size: 15px;
  }

  .impborderleft {
    border-left: 1px solid #eaeaea;
  }

  .font17 {
    font-size: 17px;
  }

  .down_zi {
    font-size: 16px;
    color: #01509f;
    cursor: pointer;
  }

  .uploadk {
    border-radius: 8px;

    padding: 20px 0px;
    font-size: 15px;
    color: #999;
  }


  .avatar-uploader {
    width: 100%;
    text-align: center;
  }

  .impzi1 {
    font-size: 16px;
    color: #666;

  }

  .impzi2 {
    font-size: 15px;
    color: #999;
    margin-top: 5px;
  }

  .importcontent {
    padding: 20px;
    display: flex;
    flex-wrap: wrap;
    font-size: 15px;
    color: #666;
    background-color: #f3f8fb;
    border-radius: 8px;
    line-height: 25px;
  }

  .downpng {
    background: url(@/assets/image/cf/img19.png) no-repeat center right 8px;
    padding-right: 25px;
    background-size: 15px 15px;
  }
}
</style>

<style lang="scss">
.boardBox1 .el-upload {
  width: auto !important;
}
</style>
